package de.hsb.ai.agent.TeamDetectiveAgent;

import java.io.IOException;
import java.util.List;
import java.util.Vector;

import org.jgrapht.Graphs;

import de.hsb.ai.util.map.ScotlandJadeMap;
import de.hsb.ai.util.map.ScotlandJadeMapHelper.ScotlandJadeVertex;

public class DistanceFinder {

	ScotlandJadeMap map;
	
	public DistanceFinder(ScotlandJadeMap map){
		this.map = map;
	}
	
	/**
	 *  Gets the distance from the lookup table, without calculation. 
	 */
	protected int getDistance(ScotlandJadeVertex from, ScotlandJadeVertex to){
		PersistenceManager pm = new PersistenceManager();
		int i = -1;
		try {
			i = pm.load(from.getIndex(),to.getIndex());
//			System.out.println("DISTANCE FROM LOOKUP TABLE: "+i);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return i;
	}
	
	/**
	 *  Calculates the shortest distance of 2 nodes with breadth first search. 
	 */
	protected int measureDistance(ScotlandJadeVertex from, ScotlandJadeVertex to) {
		int distance = 0;
		List<ScotlandJadeVertex> openList = Graphs.neighborListOf(map, from);
		List<ScotlandJadeVertex> pastOpenList = Graphs.neighborListOf(map, from);
		pastOpenList.clear();
		openList.clear();
		openList.add(from);
		
		while(true){
			pastOpenList.clear();
			for (int i = 0; i < openList.size(); i++) {
				pastOpenList.add(openList.get(i));
			}
			openList.clear();
			for (int i = 0; i < pastOpenList.size(); i++) {
				List<ScotlandJadeVertex> neighbours = Graphs.neighborListOf(map, pastOpenList.get(i)); 
				for (int j = 0; j < neighbours.size(); j++) {
					openList.add(neighbours.get(j));
				}
			}
			distance++;
			
			for (int i = 0; i < openList.size(); i++) {
//					System.out.println(openList.get(i).getIndex()+" "+from.getIndex()+" "+to.getIndex()+" "+distance);
				if(openList.get(i).getIndex() == to.getIndex()){
					return distance;
				}
			}
			if(distance == 15) return distance;
		}
	}
	
	/**
	 * Creates a table with approximately 40000 entries for all distances.
	 */
	private void createMoveDistanceTable() {
		PersistenceManager pm = new PersistenceManager(); 
		Vector<String> v = new Vector<String>();
		
		for (int i = 1; i < 200; i++) {
			for (int j = 1; j < 200; j++) {
				v.add(measureDistance(map.get(i), map.get(j))+";");
			}
			v.add("\r\n");
		}
		try {
			pm.save(v);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
